<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\Request;
use think\facade\Db;

class Index extends Base
{
    protected $middleware = [
        '\app\index\middleware\HeaderNav',
        '\app\index\middleware\UserLogin'
    ];

    public function index(Request $request)     //博客首页
    {
        $list = Db::table('post_cate')
            ->where('status',0)
            ->field('id,cate_name,cate_introduce,cate_logo')
            ->select()
            ->toArray();


        return view('',['list'=>$list]);
    }

    public function lists($limit=3,$page=1){    //分类文章列表

        $id = $this->request->get('id');

        if(empty($id)){
            return redirect('index');
        }
        $cate = Db::table('post_cate')->where('id',$id)->field('id,cate_name')->find(); //查询分类信息

        return view('',['cate'=>$cate]);
    }

    public function data()      //文章列表
    {
        $limit = (int)$this->request->get('limit');
        $page = $this->request->get('page');
        $id = $this->request->get('id');

        $offset = ($page-1)*$limit;


        $post_list = Db::table('posts')     //分类帖子列表
        ->alias('p')
            ->leftJoin('admin a','a.id=p.user_id')
            ->where([['p.cate_id','=',$id],['p.status','=',0]])
            ->field('p.id,a.admin_name,p.post_title,p.cate_id,p.post_img,p.user_id,p.post_content,p.views,p.create_time')
            ->limit($offset,$limit)
            ->select()
            ->toArray();



        $count = Db::table('posts')        //分页总页数
        ->where([['cate_id','=',$id],['status','=',0]])
            ->count();

        $total_page = (int)ceil($count/$limit);

        return json(['code'=>200,'msg'=>"查询成功",'data'=>$post_list,'total_page'=>$total_page]);
    }

    public function postInfo($post_id,$user_id)  //入参1 文章id 2用户id
    {
        $list = Db::table('posts')
            ->alias('p')
            ->leftJoin('post_cate p_c','p.cate_id=p_c.id')
            ->leftJoin('admin a','p.user_id=a.id')
            ->where('p.id',$post_id)
            ->where('p.user_id',$user_id)
            ->field('p.id,p.post_title,p.post_content,p.user_id,p.views,p_c.cate_name,p.create_time,a.admin_name')
            ->find();

        return view('',['list'=>$list]);
    }

    public function test()
    {
        return view();
    }
}
